package com.yjf.ljr.util;

import java.io.File;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.yjf.ljr.R;
import com.yjf.ljr.activity.IjActivity;
import com.yjf.ljr.adapter.CommonAdapter;
import com.yjf.ljr.adapter.CommonAdapter.HandleCallBack;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;

public class AppUtil {
	public static boolean haveInstallApp(Context context, String packageName) {
		if (null == packageName || packageName.trim().length() == 0) {
			return false;
		}
		PackageInfo packageInfo;
		try {
			packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);

		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}
		if (packageInfo == null) {
			return false;
		}
		return true;
	}

	public static void launchApp(Context ctx, String pkgName) {
		PackageManager packageManager = ctx.getPackageManager();
		Intent intent = new Intent();
		intent = packageManager.getLaunchIntentForPackage(pkgName);
		ctx.startActivity(intent);
	}

	public static boolean isNetAvailable(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivityManager == null) {
			return false;
		} else {
			NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
			if (networkInfo != null && networkInfo.isConnected()) {
				if (networkInfo.getState() == NetworkInfo.State.CONNECTED)
					return true;
			}
			return false;
		}
	}

	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * Title:以date时间转换成format格式输出
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param date
	 *            日期
	 * @param format
	 *            yyyyMMddkkmm、yyyy-MM-dd"、MM月dd日、yyyyMMddHHmmss、yyyyMMddHHmm
	 * @return
	 */
	public static String getCurrentTime(String format, long inTimeInMillis) {
		return DateFormat.format(format, inTimeInMillis).toString();
	}

	public static long timeString2Long(String format, String time) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		long millionSeconds = 0;
		try {
			millionSeconds = sdf.parse(time).getTime();// 毫秒
		} catch (Exception e) {
			e.printStackTrace();
		}
		return millionSeconds;
	}

	public static boolean isNumeric(String str) {
		if (null == str) {
			return false;
		}
		Pattern pattern = Pattern.compile("[0-9]+");
		return pattern.matcher(str).matches();
	}

	public static String getDeviceName() {
		String manufacturer = Build.MANUFACTURER;
		String model = Build.MODEL;
		if (model.startsWith(manufacturer)) {
			return capitalize(model);
		} else {
			return capitalize(manufacturer) + " " + model;
		}
	}

	private static String capitalize(String s) {
		if (s == null || s.length() == 0) {
			return "";
		}
		char first = s.charAt(0);
		if (Character.isUpperCase(first)) {
			return s;
		} else {
			return Character.toUpperCase(first) + s.substring(1);
		}
	}

	/**
	 * Title: 获取手机Imei，Imsi
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param ctx
	 * @param type
	 *            "imei" / "imsi"
	 * @return
	 */
	public static String getImei(Context ctx, String type) {
		String result = "";
		TelephonyManager mTelephonyMgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
		if ("imei".equals(type)) {
			result = mTelephonyMgr.getDeviceId();
		} else if ("imsi".equals(type)) {
			result = mTelephonyMgr.getSubscriberId();
		}
		return TextUtils.isEmpty(result) ? "" : result;
	}

	/**
	 * 获取渠道号
	 */
	public static String getChanel(Context ctx) {
		Object value = null;
		try {
			ApplicationInfo ai = ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(),
					PackageManager.GET_META_DATA);
			value = ai.metaData.get("CHANNEL");
		} catch (Exception e) {
		}
		return value != null ? value.toString() : "";
	}

	/**
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param ctx
	 * @return /data/app/com.test-1.apk
	 */
	public static String getSourceDir(Context ctx) {
		String value = null;
		try {
			ApplicationInfo ai = ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(),
					PackageManager.GET_META_DATA);
			value = ai.sourceDir;
		} catch (Exception e) {
		}
		return value != null ? value.toString() : "";
	}

	// 获取versionName
	public static String getVersionName(Context context) {
		try {
			PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return pi.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "";
		}
	}

	// 获取versionCode
	public static int getVersionCode(Context context) {
		try {
			PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return pi.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return 0;
		}
	}

	/**
	 * 获取mac地址
	 * 
	 * @return
	 */
	public static String getMacAdress(Context context) {
		WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		if (info != null && info.getMacAddress() != null) {
			return info.getMacAddress();
		} else {
			return "";
		}
	}

	public static enum TextType {
		TYPE_TEXT, TYPE_HTML
	};

	/**
	 * 设置TextView文本
	 * 
	 * @param v
	 *            TextView, EditText, Button
	 * @param text
	 *            设置的内容
	 * @param hide
	 *            在text为空时是否隐藏
	 * @param type
	 *            TextType
	 */
	public static void setViewText(View v, CharSequence text, boolean hide, TextType type) {
		if (v == null) {
			return;
		} else {
			if (TextUtils.isEmpty(text) && hide) {
				v.setVisibility(View.GONE);
				return;
			}
		}
		v.setVisibility(View.VISIBLE);

		if (type == TextType.TYPE_HTML) {
			text = Html.fromHtml((String) text);
		}
		if (v instanceof TextView) {
			((TextView) v).setText(text);
		} else if (v instanceof EditText) {
			((EditText) v).setText(text);
		} else if (v instanceof Button) {
			((Button) v).setText(text);
		}
	}

	/**
	 * 设置TextView文本, 不隐藏
	 * 
	 * @param v
	 *            TextView, EditText, Button
	 * @param text
	 *            设置的内容
	 */
	public static void setViewText(TextView tv, CharSequence text) {
		setViewText(tv, text, false, TextType.TYPE_TEXT); // 不隐藏
	}

	/**
	 * 设置TextView文本, 不隐藏
	 * 
	 * @param v
	 *            TextView, EditText, Button
	 * @param text
	 *            设置的内容
	 */
	public static void setViewHtml(View v, String text) {
		setViewText(v, text, false, TextType.TYPE_HTML); // 不隐藏
	}

	/**
	 * 图片圆角化
	 * 
	 * @param bitmap
	 * @param pixels
	 * @return
	 */
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	@SuppressWarnings("deprecation")
	public static Drawable toRoundCorner(Drawable drawable, int pixels) {
		Bitmap b = ((BitmapDrawable) drawable).getBitmap();
		return new BitmapDrawable(toRoundCorner(b, 10));
	}

	/**
	 * 获取屏幕宽度
	 * 
	 * @param context
	 * @return
	 */
	public static int getDisplayWidth(Context context) {
		DisplayMetrics metric = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metric);
		return metric.widthPixels;
	}

	/**
	 * 获取屏幕高度
	 * 
	 * @param context
	 * @return
	 */
	public static int getDisplayHeight(Context context) {
		DisplayMetrics metric = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metric);
		return metric.heightPixels;
	}

	/**
	 * 获取SD卡的路径
	 * 
	 * @return sd卡的 路径，如果不存在，则返回""
	 */
	public static String getSDPath() {
		if (isSDCardMounted()) {
			File sdDir = Environment.getExternalStorageDirectory();// 获取根目录
			System.out.println("根目录" + sdDir.toString());
			return sdDir.toString();
		} else {
			return "";
		}
	}

	/**
	 * 判断SD卡是否加载
	 * 
	 * @return
	 */
	public static boolean isSDCardMounted() {
		return Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
	}

	/**
	 * 安装apk
	 */
	public static void installApk(Context ctx, File apkfile) {
		if (apkfile != null && apkfile.exists()) {
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
			ctx.startActivity(i);
		}
	}

	// 得到网络类型
	public static String getNetWorkType(Context context) {
		String nt = "";
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			nt = "WIFI";
		} else {
			TelephonyManager telMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			switch (telMgr.getNetworkType()) {
			case TelephonyManager.NETWORK_TYPE_EDGE:
				nt = "EDGE";
				break;
			case TelephonyManager.NETWORK_TYPE_GPRS:
				nt = "GPRS";
				break;
			case TelephonyManager.NETWORK_TYPE_UMTS:
				nt = "UMTS";
				break;
			case TelephonyManager.NETWORK_TYPE_HSDPA:
				nt = "HSDPA";
				break;
			case TelephonyManager.NETWORK_TYPE_1xRTT:
				nt = "1xRTT";
				break;
			case TelephonyManager.NETWORK_TYPE_CDMA:
				nt = "CDMA";
				break;
			case TelephonyManager.NETWORK_TYPE_EVDO_0:
				nt = "EVDO_0";
				break;
			case TelephonyManager.NETWORK_TYPE_EVDO_A:
				nt = "EVDO_A";
				break;
			case TelephonyManager.NETWORK_TYPE_HSPA:
				nt = "HSPA";
				break;
			case TelephonyManager.NETWORK_TYPE_HSUPA:
				nt = "HSUPA";
				break;
			default:
				nt = "TD-SCDMA";
				break;
			}
		}
		return nt;
	}

	public static void callNumber(Context ctx, String number) {
		if (!TextUtils.isEmpty(number)) {
			// ctx.startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
			// + number)));

			Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number));
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			ctx.startActivity(intent);
		}
	}

	/**
	 * 对象的属性拷贝
	 * 
	 * @param objDesc
	 *            赋值对象
	 * @param objSrc
	 *            数据源
	 */
	public boolean copy(Object objDesc, Object objSrc) {
		if (objSrc == null) {
			return false;
		}
		Class<?> clazz = objSrc.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			try {
				field.set(objDesc, field.get(objSrc));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return true;
	}

	/**
	 * 获取弹出式 PopupWindow
	 * 
	 * @param ctx
	 * @param adapter
	 *            list适配器
	 * @param title
	 *            标题
	 * @param vSet
	 *            设置点击后的值
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static PopupWindow getPopupWindow(Context ctx, final CommonAdapter adapter, String title, final View vSet) {
		View v = View.inflate(ctx, R.layout.popmenu_bank, null);
		final PopupWindow popMenu = new PopupWindow(v, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		ListView lvPopMenu = (ListView) v.findViewById(R.id.lvPopMenu);
		lvPopMenu.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (vSet instanceof TextView) {
					((TextView) vSet).setText((String) adapter.getItem(position));
				} else if (vSet instanceof ImageView) {
					((ImageView) vSet).setImageResource((Integer) adapter.getItem(position));
				}
				popMenu.dismiss();
			}
		});
		v.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				popMenu.dismiss();
			}
		});
		lvPopMenu.setAdapter(adapter);
		((TextView) v.findViewById(R.id.tvTitlePopmenu)).setText(title);

		popMenu.setFocusable(true);
		popMenu.setOutsideTouchable(true);
		popMenu.update();
		popMenu.setBackgroundDrawable(new BitmapDrawable());
		return popMenu;
	}

	public interface HandlerItemCallBack {
		public void handle(AdapterView<?> parent, View view, int position, long id);
	}

	@SuppressWarnings("deprecation")
	public static PopupWindow getPopupWindow(Context ctx, final CommonAdapter adapter, String title,
			final HandlerItemCallBack handlerItemCallBack) {
		View v = View.inflate(ctx, R.layout.popmenu_bank, null);
		final PopupWindow popMenu = new PopupWindow(v, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		ListView lvPopMenu = (ListView) v.findViewById(R.id.lvPopMenu);
		lvPopMenu.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				handlerItemCallBack.handle(parent, view, position, id);
				popMenu.dismiss();
			}
		});
		v.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				popMenu.dismiss();
			}
		});
		lvPopMenu.setAdapter(adapter);
		((TextView) v.findViewById(R.id.tvTitlePopmenu)).setText(title);

		popMenu.setFocusable(true);
		popMenu.setOutsideTouchable(true);
		popMenu.update();
		popMenu.setBackgroundDrawable(new BitmapDrawable());
		return popMenu;
	}

	public static PopupWindow getPopupWindow(Context ctx, final CommonAdapter adapter, String title, final View vSet,
			final HandlerItemCallBack handlerItemCallBack) {
		View v = View.inflate(ctx, R.layout.popmenu_bank, null);
		final PopupWindow popMenu = new PopupWindow(v, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		ListView lvPopMenu = (ListView) v.findViewById(R.id.lvPopMenu);
		lvPopMenu.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (vSet instanceof TextView) {
					((TextView) vSet).setText((String) adapter.getItem(position));
				} else if (vSet instanceof ImageView) {
					((ImageView) vSet).setImageResource((Integer) adapter.getItem(position));
				}
				handlerItemCallBack.handle(parent, view, position, id);
				popMenu.dismiss();
			}
		});
		v.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				popMenu.dismiss();
			}
		});
		lvPopMenu.setAdapter(adapter);
		((TextView) v.findViewById(R.id.tvTitlePopmenu)).setText(title);

		popMenu.setFocusable(true);
		popMenu.setOutsideTouchable(true);
		popMenu.update();
		popMenu.setBackgroundDrawable(new BitmapDrawable());
		return popMenu;
	}

	/**
	 * 设置EditText hint的大小
	 * 
	 * @param et
	 *            EditText
	 * @param hint
	 *            hint文本
	 * @param size
	 *            hint的大小
	 */
	public static void setEditTextHintSize(EditText et, String hint, int size) {
		SpannableString ss = new SpannableString(hint);
		AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size, true); // 新建一个属性对象,设置文字的大小
		ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 附加属性到文本
		et.setHint(new SpannedString(ss)); // 设置hint, 一定要进行转换,否则属性会消失
	}

	/**
	 * 将货币金额转换成数字
	 * 
	 * @param str
	 *            金额
	 * @param pattern
	 *            格式
	 * @return
	 */
	public static double moneyToNum(String str) {
		double output = 0.0d;
		if (!TextUtils.isEmpty(str)) {
			String result = str.replace(",", "");
			try {
				output = Double.parseDouble(result);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return output;
	}

	/**
	 * 将金额显示为货币格式
	 * 
	 * @param str
	 * @param pattern
	 * @return
	 */
	public static String getAmountString(String str, String pattern) {
		if (pattern == null) {
			pattern = ",##0.00";
		}
		DecimalFormat myFormatter = new DecimalFormat(pattern);
		String output = myFormatter.format(Double.parseDouble(str));
		return output;
	}

	// 判断一个字符串是否含有数字
	public static boolean isCharAllSame(String content) {
		if (TextUtils.isEmpty(content)) {
			return false;
		}
		char first = content.charAt(0);
		char[] chars = content.toCharArray();
		for (char sub : chars) {
			if (first != sub) {
				return false;
			}
		}
		return true;
	}

	// 判断一个字符串是否含有数字

	public static boolean hasDigit(String content) {
		if (TextUtils.isEmpty(content)) {
			return false;
		}
		boolean result = false;
		Pattern p = Pattern.compile(".*\\d+.*");
		Matcher m = p.matcher(content);
		if (m.matches())
			result = true;
		return result;
	}
	// 判断email格式是否正确
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}
	
	// 判断phone格式是否正确
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}
	
	// 判断是不是中文
	public static boolean isChinese(String name) {
		String str = "^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$";			
		boolean isIncludeChinese = false;
		for( int i = 0; i < name.length (); i++ ) {
			if( Pattern.matches( str , name.substring ( i, i + 1 ) ) ) {
				isIncludeChinese = true;
				break;
			}
		}
		return isIncludeChinese;
	}

	/*** 当额度上万元显示万汉字单位和 **/
	public static String changeMoneyCompany(String money) {
		String dealResult = "";
		if (!TextUtils.isEmpty(money)) {
			double borrowMoney = 0;
			try {
				borrowMoney = Double.parseDouble(money.replace(",", ""));
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (borrowMoney < 10000) {
				dealResult = borrowMoney + "";
			} else {
				int tenThousand = (int) borrowMoney / 10000;
				double thousand = (borrowMoney % 10000) / 10000d;
				if (thousand > 0) {
					dealResult = ((tenThousand + thousand) + "万");
				} else {
					dealResult = (tenThousand + ".00万");
				}
			}

		}
		return dealResult;
	}
}